package com.honeywen.mymvc.leetcode;

/**
 * @author weiw@opera.com
 * @date 2018/10/8 下午12:36
 */
public class SqrtTest {

    public static void main(String[] args) {
        System.out.println(mySqrt(2147395600));
        System.out.println(mySqrt2(2147395600));
        System.out.println(mySqrt(4));
        System.out.println(mySqrt2(4));

    }

    public static int mySqrt2(int x) {
        if (x <= 0) {
            return 0;
        }

        for (int i = 0; i < x; i++) {
            boolean flag = (long) i * (long) i <= x && (long) (i + 1) * (long) (i + 1) > x;
            if (flag) {
                return i;
            }
        }

        return 0;

    }


    public static int mySqrt(int x) {

        if (x <= 0) {
            return 0;
        }
        int max = x / 2 + 1;
        int min = 0;
        while (min <= max) {
            int mid = min + (max - min) / 2;
            long rs = (long) mid * (long) mid;
            if (rs == x) {
                return mid;
            }

            if (rs < x) {
                min = mid + 1;
            } else {
                max = mid - 1;
            }
        }

        return max;

    }
}
